package com.ict.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ict.api.dto.IctCartItemDTO;
import com.ict.api.entity.IctCartItem;
import com.ict.api.entity.IctOrder;
import com.ict.api.entity.IctOrderItem;
import com.ict.api.entity.IctProduct;
import com.ict.api.entity.IctSkuStock;
import com.ict.api.result.ApiResponse;
import com.ict.api.vo.IctCartItemVO;
import com.ict.api.vo.IctOrderVO;
import com.ict.mapper.IctCartItemMapper;
import com.ict.mapper.IctProductMapper;
import com.ict.mapper.IctSkuStockMapper;
import com.ict.service.IctCartItemService;
import com.ict.service.IctOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 购物车表 服务实现类
 * </p>
 *
 * @author wjp
 * @since 2025-03-23
 */
@Service
public class IctCartItemServiceImpl extends ServiceImpl<IctCartItemMapper, IctCartItem> implements IctCartItemService {

    @Resource
    private IctCartItemMapper cartMapper;

    @Resource
    private IctProductMapper productMapper;

    @Resource
    private IctSkuStockMapper stockMapper;

    @Resource
    private IctOrderService orderService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResponse<String> addCartItem(IctCartItemDTO cartItemAddDTO) {
        // 查询商品信息
        IctProduct product = productMapper.selectById(cartItemAddDTO.getProductId());
        if (product == null) {
            return ApiResponse.error("商品不存在");
        }

        // 查询购物车中是否已有该商品
        LambdaQueryWrapper<IctCartItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(IctCartItem::getUserId, cartItemAddDTO.getUserId())
                .eq(IctCartItem::getProductId, cartItemAddDTO.getProductId())
                .eq(IctCartItem::getProductSkuId, cartItemAddDTO.getProductSkuId());

        IctCartItem cartItem = cartMapper.selectOne(queryWrapper);

        if (cartItem != null) {
            // 更新购物车商品数量
            LambdaUpdateWrapper<IctCartItem> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.setSql("quantity = quantity + " + cartItemAddDTO.getQuantity())
                    .eq(IctCartItem::getId, cartItem.getId());

            cartMapper.update(null, updateWrapper);
        } else {
            // 添加新的购物车商品
            cartItem = new IctCartItem();
            cartItem.setUserId(cartItemAddDTO.getUserId());
            cartItem.setProductId(cartItemAddDTO.getProductId());
            cartItem.setProductSkuId(cartItemAddDTO.getProductSkuId());
            cartItem.setQuantity(cartItemAddDTO.getQuantity());
            cartItem.setPrice(product.getPrice());

            cartMapper.insert(cartItem);
        }

        return ApiResponse.success("添加成功");
    }

    @Override
    public ApiResponse<List<IctCartItemVO>> getCartList(IctCartItemDTO cartQueryDTO) {
        // 查询购物车商品
        List<IctCartItem> cartItems = cartMapper.selectList(
                new LambdaQueryWrapper<IctCartItem>()
                        .eq(IctCartItem::getUserId, cartQueryDTO.getUserId())
        );

        // 转换为 VO 视图对象
        List<IctCartItemVO> cartItemVOList = cartItems.stream().map(cartItem -> {
            IctCartItemVO cartItemVO = new IctCartItemVO();
            cartItemVO.setId(cartItem.getId());
            cartItemVO.setProductId(cartItem.getProductId());
            cartItemVO.setProductSkuId(cartItem.getProductSkuId());
            cartItemVO.setProductName(cartItem.getProductName());
            cartItemVO.setQuantity(cartItem.getQuantity());
            cartItemVO.setPrice(cartItem.getPrice());
            cartItemVO.setProductPic(cartItem.getProductPic());
            return cartItemVO;
        }).collect(Collectors.toList());

        return ApiResponse.success(cartItemVOList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResponse<String> updateCartItem(IctCartItemDTO cartItemUpdateDTO) {
        // 检查购物车商品是否存在
        IctCartItem cartItem = cartMapper.selectById(cartItemUpdateDTO.getId());
        if (cartItem == null) {
            return ApiResponse.error("购物车商品不存在");
        }

        // 更新购物车商品数量
        LambdaUpdateWrapper<IctCartItem> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .set(IctCartItem::getQuantity, cartItemUpdateDTO.getQuantity())
                .eq(IctCartItem::getId, cartItemUpdateDTO.getId());

        int updated = cartMapper.update(null, updateWrapper);
        if (updated > 0) {
            return ApiResponse.success("更新成功");
        } else {
            return ApiResponse.error("更新失败，请稍后重试");
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResponse<String> removeCartItem(Long cartId) {
        // 查询购物车商品是否存在
        IctCartItem cartItem = cartMapper.selectById(cartId);
        if (cartItem == null) {
            return ApiResponse.error("购物车商品不存在");
        }

        // 删除购物车商品
        int deleted = cartMapper.deleteById(cartId);
        if (deleted > 0) {
            return ApiResponse.success("删除成功");
        } else {
            return ApiResponse.error("删除失败，请稍后重试");
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResponse<IctOrderVO> checkoutCart(IctCartItemDTO cartCheckoutDTO) {
        // 查询用户购物车商品
        List<IctCartItem> cartItems = cartMapper.selectList(
                new LambdaQueryWrapper<IctCartItem>().eq(IctCartItem::getUserId, cartCheckoutDTO.getUserId())
        );

        if (CollectionUtils.isEmpty(cartItems)) {
            return ApiResponse.error("购物车为空，无法结算");
        }

        // 校验库存是否足够
        for (IctCartItem cartItem : cartItems) {
            IctSkuStock stock = stockMapper.selectOne(new LambdaQueryWrapper<IctSkuStock>()
                    .eq(IctSkuStock::getProductId, cartItem.getProductId()));

            if (stock == null || stock.getStock() < cartItem.getQuantity()) {
                return ApiResponse.error("商品库存不足：" + cartItem.getProductId());
            }
        }

        // 生成订单明细
        List<IctOrderItem> orderItems = cartItems.stream().map(cartItem -> {
            IctOrderItem orderItem = new IctOrderItem();
            orderItem.setProductId(cartItem.getProductId());
            orderItem.setProductSkuId(cartItem.getProductSkuId());
            orderItem.setProductQuantity(cartItem.getQuantity());
            orderItem.setProductPrice(cartItem.getPrice());
            return orderItem;
        }).collect(Collectors.toList());

        // 创建订单
        IctOrder order = orderService.createOrder(cartCheckoutDTO.getUserId(), cartCheckoutDTO.getPaymentType(), orderItems);

        // 锁定库存
        for (IctCartItem cartItem : cartItems) {
            LambdaUpdateWrapper<IctSkuStock> stockUpdateWrapper = new LambdaUpdateWrapper<>();
            stockUpdateWrapper
                    .setSql("stock = stock - " + cartItem.getQuantity() + ", lock_stock = lock_stock + " + cartItem.getQuantity())
                    .eq(IctSkuStock::getProductId, cartItem.getProductId())
                    .ge(IctSkuStock::getLockStock, cartItem.getQuantity()); // 确保锁定库存足够
            stockMapper.update(null, stockUpdateWrapper);
        }

        // 清空购物车
        cartMapper.delete(new LambdaQueryWrapper<IctCartItem>().eq(IctCartItem::getUserId, cartCheckoutDTO.getUserId()));

        IctOrderVO ictOrderVO = new IctOrderVO();
        ictOrderVO.setOrderId(order.getId());
        return ApiResponse.success("订单创建成功", ictOrderVO);
    }
}
